package com.ineatconseil.yougo.services.auth;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;
import org.dozer.Mapper;

import com.ineatconseil.yougo.beans.User;
import com.ineatconseil.yougo.dto.UserDto;
import com.ineatconseil.yougo.exceptions.AuthenticationException;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.services.rest.RestPath;
import com.ineatconseil.yougo.services.rest.RestServiceInvoker;

/**
 * Basic Security Realm implementation.
 * 
 * @author johanblo
 * 
 */
public class BasicAuthenticator implements Authenticator {

	public static final String AUTH_TOKEN = "authToken";

	@Inject
	private RestServiceInvoker restServiceInvoker;

	@Inject
	private Mapper mapper;

	@Inject
	private Request request;

	public void login(String username, String password) throws AuthenticationException {

		try {

			restServiceInvoker.initClient(username, password);

			List<RestPath> paths = new ArrayList<RestPath>();
			paths.add(new RestPath("users", username));

			UserDto userDto = restServiceInvoker.call(paths, UserDto.class);

			if (userDto == null) {
				throw new AuthenticationException("The user doesn't exist");
			}

			User user = mapper.map(userDto, User.class);

			request.getSession(true).setAttribute(AUTH_TOKEN, user);

		} catch (RestServiceException e) {
			throw new AuthenticationException("The user doesn't exist");
		}

	}

	public boolean isLoggedIn() {
		Session session = request.getSession(false);
		if (session != null) {
			return session.getAttribute(AUTH_TOKEN) != null;
		}
		return false;
	}

	public void logout() {
		Session session = request.getSession(false);
		if (session != null) {
			session.setAttribute(AUTH_TOKEN, null);
			session.invalidate();
		}
	}

	public User getLoggedUser() {
		User user = null;

		if (isLoggedIn()) {
			user = (User) request.getSession(true).getAttribute(AUTH_TOKEN);
		} else {
			throw new IllegalStateException("The user is not logged ! ");
		}
		return user;
	}

}
